package com.sshtools.start;

import java.awt.EventQueue;
import java.io.File;
import java.util.Map;

import com.jcraft.jsch.Session;
import com.sshtools.utils.SSHUtils;
import com.sshtools.view.MainView;

import tsif.component.log.Log;
import tsif.utils.FileUtils;
import tsif.utils.StringUtils;
import tsif.utils.SystemUtils.ArgUtils;

public class SSHStart {

	public static void run(String[] args) {
		// 参数启动解析
		Map<String, String> params = ArgUtils.systemArgs(args);
		ConfigMgr.init(params);

		// 帮助
		boolean helpMode = ArgUtils.get(params, ConfigMgr.SYSARG_HELP, false);
		if (helpMode) {
			String helpStr = ArgUtils.createHelpString(new Object[] { //
					ConfigMgr.SYSARG_HELP, //
					ConfigMgr.SYSARG_COMMON, //
					"指令模式", //
					ConfigMgr.SYSARG_C_HOST, //
					ConfigMgr.SYSARG_C_PORT, //
					ConfigMgr.SYSARG_C_USENAME, //
					ConfigMgr.SYSARG_C_PASSWORD, //
					ConfigMgr.SYSARG_C_REMOTEPATH, //
					ConfigMgr.SYSARG_C_EXECCMD, //
					ConfigMgr.SYSARG_C_SHFILE, //
					ConfigMgr.SYSARG_C_UPLOADFILE, //
					ConfigMgr.SYSARG_C_FINSIHCLEAN, //
					ConfigMgr.SYSARG_C_TIMEOUT, //
					"视图模式", //
					ConfigMgr.SYSARG_SERVERXMLPATH,//
			});
			Log.info(helpStr);
			return;
		}

		// 识别启动方式
		boolean commonMode = ArgUtils.get(params, ConfigMgr.SYSARG_COMMON, false);
		if (commonMode) {
			// 启动命令行模式
			runCommond(params);
			return;
		}

		// 启动视图页面
		runView(params);

	}

	/** 运行视图 **/
	public static void runView(Map<String, String> params) {
		// 创建任务
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					// 创建窗口
					MainView window = new MainView();
					// 加载配置
					String serverXmlPath = ArgUtils.get(params, ConfigMgr.SYSARG_SERVERXMLPATH, "conf/servers.xml");
					window.reloadServers(serverXmlPath);
					// 显示
					window.show();
					Log.info("启动成功");
				} catch (Throwable e) {
					Log.error("窗口启动错误! ", e);
				}
			}
		});
	}

	/** 运行命令行 **/
	public static void runCommond(Map<String, String> params) {
		Log.info("commond run: " + params);
		String host = ArgUtils.get(params, ConfigMgr.SYSARG_C_HOST, "");
		int port = ArgUtils.get(params, ConfigMgr.SYSARG_C_PORT, 0);
		String username = ArgUtils.get(params, ConfigMgr.SYSARG_C_USENAME, "");
		if (StringUtils.isEmpty(host) //
				|| StringUtils.isEmpty(username) //
				|| port <= 0 //
		) {
			Log.error("服务器参数缺失! host=\"" + host + "\" port=" + port + " username=\"" + username + "\"");
			return;
		}
		// 远程目录
		String remotePath = ArgUtils.get(params, ConfigMgr.SYSARG_C_REMOTEPATH, "");
		if (StringUtils.isEmpty(remotePath)) {
			Log.error("远程目录没有设置!");
			return;
		}

		// 检测sh文件
		String shfile = ArgUtils.get(params, ConfigMgr.SYSARG_C_SHFILE, "");
		String uploadfile = ArgUtils.get(params, ConfigMgr.SYSARG_C_UPLOADFILE, "");
		String execCmd = ArgUtils.get(params, ConfigMgr.SYSARG_C_EXECCMD, "");
		if (StringUtils.isEmpty(shfile) //
				&& StringUtils.isEmpty(uploadfile) //
				&& StringUtils.isEmpty(execCmd) //
		) {
			Log.error("没有操作, 操作文件/上传/指令必须有一项.");
			return;
		}

		// 检测文件
		File uploadFile = null;
		if (!StringUtils.isEmpty(uploadfile)) {
			uploadFile = new File(uploadfile);
			if (!uploadFile.exists()) {
				Log.error("上传文件不存在! " + uploadFile.getAbsolutePath());
				return;
			}
		}
		// 检测文件
		File shFile = null;
		if (!StringUtils.isEmpty(shfile)) {
			shFile = new File(shfile);
			if (!shFile.exists()) {
				Log.error("sh文件不存在! " + shFile.getAbsolutePath());
				return;
			}
		}
		String password = ArgUtils.get(params, ConfigMgr.SYSARG_C_PASSWORD, "");
		int timeout = ArgUtils.get(params, ConfigMgr.SYSARG_C_TIMEOUT, 10 * 1000);
		boolean finishClean = ArgUtils.get(params, ConfigMgr.SYSARG_C_FINSIHCLEAN, true);

		// 执行连接
		Session session = null;
		String resultStr = null;
		try {
			// 执行连接
			session = SSHUtils.connect(host, port, username, password, null, timeout);
			SSHUtils.execCmd(session, "mkdir " + remotePath);

			// 执行操作
			if (uploadFile != null) {
				Log.info("upload " + remotePath + "/" + uploadFile.getName());
				resultStr = SSHUtils.execUpload(session, uploadFile, remotePath);
				Log.info(resultStr);
			}

			// 上传脚本
			if (shFile != null) {
				Log.info("upload " + remotePath + "/" + shFile.getName());
				resultStr = SSHUtils.execUpload(session, shFile, remotePath);
				Log.info(resultStr);

				// 执行
				String shfileName = FileUtils.getFileName(shFile.getName());
				String cmd = "sh " + remotePath + "/" + shfileName;
				Log.info("exec " + cmd);
				resultStr = SSHUtils.execCmd(session, cmd, remotePath);
				// resultStr = SSHUtils.execShell(session, new String[] { cmd });
				Log.info(resultStr);
			}

			// 执行指令
			if (!StringUtils.isEmpty(execCmd)) {
				Log.info("exec " + execCmd);
				resultStr = SSHUtils.execCmd(session, execCmd, remotePath);
				Log.info(resultStr);
			}

			// 清除
			if (finishClean) {
				if (shFile != null) {
					String fileName = FileUtils.getFileName(shFile.getName());
					String remoteShFile = remotePath + "/" + fileName;
					SSHUtils.execCmd(session, "rm -rf " + remoteShFile);
				}

				if (uploadFile != null) {
					String fileName = FileUtils.getFileName(uploadFile.getName());
					String remoteShFile = remotePath + "/" + fileName;
					SSHUtils.execCmd(session, "rm -rf " + remoteShFile);
				}
			}

		} catch (Exception e) {
			Log.error("执行操作失败! ", e);
		} finally {
			if (session != null) {
				session.disconnect();
				session = null;
			}
		}

	}

	/** main 入口 **/
	public static void main(String[] args) {
		if (args == null || args.length <= 0) {
			// args = new String[] { "--help" };
			// args = new String[] { "--commond" //
			// , "--host=10.125.40.230" //
			// , "--port=36000" //
			// , "--username=user00" //
			// , "--password=SAdzt@2017" //
			// , "--remotepath=/home/user00/run" //
			// , "--execcmd=ls" //
			// , "--shfile=upload/upload.sh" //
			// , "--uploadfile=upload/package" //
			// , "--finishclean" //
			// };
		}

		run(args);
	}
}
